/** 
 * StringTokenizer.cc
 * 
 * Author: Carlos Lopes
 * Copyright(c), 2007
 */
#include <cctype>
#include <boost/regex.hpp>
#include "LADSUtil/foreach.h"
#include "LADSUtil/StringManipulator.h"
using namespace LADSUtil;

#define isvalidtoken(ch) ((ch) == ')' || (ch)== '(' || (ch) == ',' )	

std::string StringManipulator::toUpper(const std::string& str){
    std::string result;

    foreach(char _c, str){
        result.push_back(toupper(_c));
    }

    return result;
}

std::string StringManipulator::toLower(const std::string& str){
    std::string result;

    foreach(char _c, str){
        result.push_back(tolower(_c));
    }

    return result;
}

std::string StringManipulator::clean(const std::string& str){
    std::string result;
    bool started = false;

    foreach(char _c, str){
        if (isalpha(_c) || isdigit(_c) ||
            isvalidtoken(_c) ||  _c == '_' || _c == char(39) ||
            (started && _c == ' ')){
            
            result.push_back((_c > 'Z' && isalpha(_c)) ? (_c - ('z'-'Z')) : _c);
            started = true;
        }
    }

    return result;
}

std::vector<std::string> StringManipulator::split(std::string& str, const std::string& delimiter){
    unsigned int cutAt;
    std::vector<std::string> tokens;
    
    while ((cutAt = str.find(delimiter)) != std::string::npos){
        if(cutAt > 0){
            tokens.push_back(str.substr(0, cutAt));
        }
        str = str.substr(cutAt + 1);
    }
    if(str.length() > 0){
        tokens.push_back(str);
    }

    return tokens;
}

void StringManipulator::trim(std::string& str){
    std::string::size_type pos = str.find_last_not_of(' ');
    if(pos != std::string::npos){
        str.erase(pos + 1);
        pos = str.find_first_not_of(' ');
        if(pos != std::string::npos){
            str.erase(0, pos);
        }
    } else {
        str.erase(str.begin(), str.end());
    }
}

bool StringManipulator::isNumber(const std::string& str){

    static const boost::regex re("[-\\+]?\\d*\\.?\\d+");
    return boost::regex_match(str, re);
}
